package com.orgname.glvone.glvtwo.web.aop;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @ClassName ControllerLogAspect
 * @Version v1.0
 */
@Aspect
@Component
public class ControllerLogAspect {
    public static final String UNIQUE_ID = "traceId";
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Around("execution(public * com.orgname.*.*.*.controller..*.*(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MDC.put(UNIQUE_ID, UUID.randomUUID().toString().replace("-", ""));
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null == attributes) {
            return null;
        }
        Object obj = null;
        long startTime = System.currentTimeMillis();
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        HttpServletRequest request = attributes.getRequest();
        try {
            obj = joinPoint.proceed();
        } finally {
            long useTime = System.currentTimeMillis() - startTime;
            logger.info("URL:{}, HTTP_METHOD: {}, IP: {} , 方法:{}, 执行时间：{} ,请求参数: {}, response：{}",
                    request.getRequestURL(), request.getMethod(), request.getRemoteAddr(), classMethod, useTime,
                    JSON.toJSONString(joinPoint.getArgs()), JSON.toJSONString(obj));
            MDC.remove(UNIQUE_ID);
        }
        return obj;
    }

    @AfterThrowing(pointcut = "execution(public * com.orgname.*.*.*.controller..*.*(..))", throwing = "e")
    public void handleThrowing(JoinPoint joinPoint, Exception e) {
        // logger.error("{}Controller异常args={}", joinPoint.getSignature().getName(), joinPoint.getArgs(), e);
    }
}
